package com.funcourse.demo.wechat.client.welet.accesstoken;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SimpleAccessTokenManager implements AccessTokenManager {

  Long accessTokenGotTime;
  AccessTokenResponse accessTokenResponse;
  @Autowired
  AccessTokenCaller accessTokenCaller;
  private static final Integer TIME_BUFFER = 30 * 1000;

  @Override
  public AccessTokenResponse getAccessToken() {
    if (needToRefreshToken()) {
      synchronized (this) {
        refreshAccessToken();
      }
    }
    return this.accessTokenResponse;
  }

  private void refreshAccessToken() {
    if (needToRefreshToken()) {
      this.accessTokenResponse = accessTokenCaller.callAccessToken();
      this.accessTokenGotTime = System.currentTimeMillis();
    }
  }

  private Boolean needToRefreshToken() {
    if (null == accessTokenResponse) {
      return true;
    }
    if (System.currentTimeMillis() - accessTokenGotTime
        >= accessTokenResponse.getExpiresInSeconds() * 1000 - TIME_BUFFER) {
      return true;
    }
    return false;
  }
}
